<script setup lang="ts">
import AddForm from './components/AddForm.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRouter, useRoute } from 'vue-router'
import { saveDataApi, getDetApi } from '@/api/logisticsCompany/index'
import { CurdData } from '@/api/logisticsCompany/types'
import { useEventBus } from '@/hooks/event/useEventBus'

const { emit } = useEventBus()
const { push, go } = useRouter()
const { query } = useRoute()
const { t } = useI18n()

const formRef = ref()
const loading = ref(false)

// 获取详情数据
const getTableDet = async () => {
  try {
    const res = await getDetApi(query.id as string)
    if (res && res.code === 0) {
      // 等待下一个 tick，确保表单组件已经挂载
      await nextTick()
      // 设置表单数据
      formRef.value?.setFormData(res.data)
    }
  } catch (error) {
    console.error('获取详情失败:', error)
  }
}

// 页面加载时获取详情
getTableDet()

// 保存
const save = async () => {
  if (!formRef.value) return

  try {
    loading.value = true
    const formData = await formRef.value.submitForm()

    if (formData) {
      const res = await saveDataApi({
        ...formData,
        id: query.id
      })

      if (res && res.code === 0) {
        emit('getList', 'editor')
        push('/logistics/company')
      }
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <ContentDetailWrap :title="t('exampleDemo.edit')" @back="push('/logistics/company')">
    <AddForm ref="formRef" />

    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </BaseButton>
    </template>
  </ContentDetailWrap>
</template>

<style scoped>
.el-select {
  width: 100%;
}
</style>
